package com.lanou3g.ssm.service;

import com.lanou3g.ssm.bean.SystemConstants;
import com.lanou3g.ssm.bean.User;
import com.lanou3g.ssm.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 按照用户账号查询用户
     * @param username
     * @return 查到返回user，查不到返回null
     */
    public User findUserByUsername(String username) {
        User condition = new User();
        condition.setUsername(username);
        List<User> userList = userMapper.selectUser(condition);
        if(userList != null && userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }

    /**
     * 用户注册
     * @param user
     * @param session
     */
    public void registerUser(User user, HttpSession session) {
        user.setCreatetime(new Date());
        user.setLastLoginTime(new Date());
        user.setStatus(SystemConstants.USER_STATUS_NORMAL);
        userMapper.insertUser(user);
        log.debug("保存用户， 自增ID: " + user.getId());
        session.setAttribute("userInfo", user);
    }

    /**
     * 查询所有收件人列表（其实就是除了自己之外的所有用户）
     * @param session
     * @return
     */
    public List<User> queryAllUserWithoutMe(HttpSession session) {
        User me = (User) session.getAttribute("userInfo");
        List<User> allUser = userMapper.selectUser(new User());
        List<User> userListWithoutMe = new ArrayList<>();
        for(User user : allUser) {
            if(!user.getId().equals(me.getId())) {
                userListWithoutMe.add(user);
            }
        }
        return userListWithoutMe;
    }

    /**
     * 有两步：
     *  <ol>
     *      <li>更新数据库User表数据</li>
     *      <li>查询数据库中User最新状态</li>
     *      <li>将最新状态更新到session中</li>
     *  </ol>
     * @param user
     */
    public void updateUser(User user, HttpSession session) {
        // 1. 第一步
        userMapper.updateUser(user);

        // 2. 第二步
        User condition = new User();
        condition.setId(user.getId());
        User newestUser = userMapper.selectUser(condition).get(0);

        // 3. 第三步
        session.setAttribute("userInfo", newestUser);
    }
}
